package com.qingzhu.controller.addressserver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.pojo.ReceivingAddress;
import com.qingzhu.pojovo.ResultVo;
import com.qingzhu.service.ReceivingAddressService;
import com.qingzhu.service.impl.ReceivingAddressServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/receiving/address/update")
public class ReceivingAddressUpdateController extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    ReceivingAddressService receivingAddressService = new ReceivingAddressServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("更改默认收货地址..");

        String id = req.getParameter("id");
        String userId = req.getParameter("userId");
        receivingAddressService.updateDefaultDreceivingAddress(Integer.parseInt(id),Integer.parseInt(userId));
        resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(200,"修改成功！")));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("修改收货地址服务..");
        String regionJson = req.getReader().readLine();
        ReceivingAddress receivingAddress = objectMapper.readValue(regionJson, ReceivingAddress.class);
        int result = receivingAddressService.updateOneReceivingAddress(receivingAddress);
        ResultVo resultVo = result > 0 ?
                new ResultVo(200,"修改成功！"):new ResultVo(500,"修改失败！");
        resp.getWriter().write(objectMapper.writeValueAsString(resultVo));
    }
}
